<template>
  <div id="mr-login">
    <div class="tab-img"><img src="../../static/img/login@2x.png" /></div>
    <div class="from">
      <tab :line-width="2" active-color="#01bcd4" bar-active-color="#01bcd4" custom-bar-width="70%">
        <tab-item selected @on-item-click="onItemClick">密码登录</tab-item>
        <div class="middle-type"><img src="../../static/img/icon_back.png" /></div>
        <tab-item @on-item-click="onItemClick">验证码登录</tab-item>
      </tab>
        <group>
            <x-input  keyboard="number" name="mobile" ref="mobile01" v-model="mobileval" is-type="china-mobile" placeholder="请输入手机号">
                <img slot="label" src="../../static/img/shouji@2x.png" >
            </x-input>
            <x-input v-show="showcolor" v-model="passwordval" type="password"  placeholder="请输入登录密码">
                <img slot="label" src="../../static/img/mima@2x.png" >
            </x-input>
            <x-input v-show="!showcolor" type="text" v-model="codeval" class="weui-vcode" placeholder="请输入短信验证码">
              <img slot="label" src="../../static/img/mima@2x.png" >
              <!-- <div slot="right" @click="sendcode" style="color:rgb(47, 120, 236);text-decoration: underline">发送验证码</div> -->
              <div class="weui-vcode-btn" style="color:rgb(47, 120, 236)"  v-bind:class="[start? 'vcode-inactive':'vcode-active']" slot="right" v-on:click="sendcode">{{setTime()}}</div>
              <countdown style="display:none" slot="right" :start="start" @on-finish="timeFinish" v-model="time"></countdown>
            </x-input>
        </group>
          <x-dialog v-show="!showcolor" v-model="showHideOnBlur" class="dialog-demo image-code" hide-on-blur>
              <x-input :show-clear="false" placeholder="请输入图形验证码" v-model="imageCode" class="weui-cell_vcode" >
                <img slot="label" src="../../static/img/mima@2x.png" >
                <img slot="right" @click="imgevent" class="weui-vcode-img" :src="urlImgCode + captchaid">
              </x-input>
            <div @click="confirmImgCode" class="confirm">
              <span>确定</span>
            </div>
          </x-dialog>
        <div v-show="showcolor">
          <div class="forget-password" v-show="showcolor" @click="forget">忘记密码？</div>
          <div class="share" @click="login">登录</div>
        </div>
        <div  v-show="!showcolor" class="share" @click="next">登录</div>
        <div class="register-other" @click="register">新用户注册</div>
    </div>
  </div>
</template>
<script>
var timeStamp = String(Number(new Date()))
import { XInput, Group, Flexbox, FlexboxItem, XButton, Tab, TabItem, TransferDomDirective as TransferDom, Countdown, XDialog } from 'vux'
import api from '../api'
import utils from '../utils'
export default {
  directives: {
    TransferDom
  },
  data () {
    return {
      time: 60,
      showcolor: true,
      start: false,
      showHideOnBlur: false,
      mobileval: '',
      passwordval: '',
      codeval: '',
      tokenval: '',
      imageCode: '',
      redirect: this.$route.query.redirect,
      urlImgCode: this.$store.state.imgvcode,
      captchaid: ''
    }
  },
  components: {
    XInput,
    Group,
    Flexbox,
    FlexboxItem,
    XButton,
    Tab,
    TabItem,
    Countdown,
    XDialog
  },
  created () {
    window.document.title = '登录'
    this.tokenval = utils.AnonToken(timeStamp)
    utils.jssdkwx(api, this.$wechat, this.$store)
  },
  methods: {
    onItemClick (index) {
      if (index === 0) {
        // 密码登录
        this.showcolor = true
      }
      if (index === 1) {
        // 验证码登录
        this.showcolor = false
      }
    },
    // 忘记密码
    forget () {
      this.$router.push('/passport/forgetPassword')
    },
    imgevent () {
      this.captchaid = '00' + utils.randomString(32)
    },
    // 跳转到注册页面
    register () {
      this.$router.push({
        path: '/passport/register',
        query: utils.toQueryParams(window.location.href)
      })
    },
    // 发送验证码
    sendcode () {
      if (this.start) {
        return
      } else if (this.mobileval === '') {
        this.$vux.toast.show({
          text: '请输入手机号',
          type: 'warn',
          width: '4rem'
        })
      } else if (this.$refs.mobile01.valid === false) {
        this.$vux.toast.show({
          text: '请输入正确手机号',
          type: 'warn',
          width: '4rem'
        })
      } else {
        api.check({
          token: this.tokenval,
          timestamp: timeStamp,
          mobile: this.mobileval
        }).then(res => {
          if (res.status === '400001002') {
            this.$vux.toast.hide()
            this.imageCode = ''
            this.showHideOnBlur = !this.showHideOnBlur
            this.captchaid = '00' + utils.randomString(32)
          } else if (res.status === '400001001') {
            this.$vux.toast.show({
              text: '手机号未注册',
              type: 'warn',
              width: '4rem'
            })
          } else {
            this.$vux.toast.show({
              text: res.message,
              type: 'warn',
              width: '4rem'
            })
          }
        })
      }
    },
    confirmImgCode () {
      var params = {
        captcha: this.imageCode,
        captchaId: this.captchaid
      }
      if (this.imageCode === '') {
        this.$vux.toast.show({
          text: '请输入图形码',
          type: 'warn',
          width: '4rem'
        })
      } else {
        api.validcode(params).then(res => {
          if (res.status === '200') {
            this.showHideOnBlur = false
            this.start = true
            this.vscode()
          } else {
            this.captchaid = '00' + utils.randomString(32)
            this.$vux.toast.show({
              text: res.message,
              type: 'warn',
              width: '4rem'
            })
          }
        })
      }
    },
    vscode () {
      api.sendCode({
        token: this.tokenval,
        timestamp: timeStamp,
        mobile: this.mobileval,
        type: 1,
        sendType: 5,
        from: 0,
        captcha: this.imageCode,
        captchaId: this.captchaid
      }).then(res => {
        console.log(res)
        if (res.status === '200') {
          this.$vux.toast.show({
            text: res.message,
            type: 'success',
            width: '4rem'
          })
        } else {
          this.$vux.toast.show({
            text: res.message,
            type: 'warn',
            width: '4rem'
          })
        }
      })
    },
    // 登录
    login () {
      var passwordReg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$/
      // 密码登录
      if (this.mobileval === '') {
        this.$vux.toast.show({
          text: '请输入手机号',
          type: 'warn',
          width: '4rem'
        })
      } else if (this.$refs.mobile01.valid === false) {
        this.$vux.toast.show({
          text: '请输入正确手机号',
          type: 'warn',
          width: '4rem'
        })
      } else {
        api.check({
          token: this.tokenval,
          timestamp: timeStamp,
          mobile: this.mobileval
        }).then(res => {
          if (res.status === '400001002') {
            this.$vux.toast.hide()
            if (this.passwordval === '') {
              this.$vux.toast.show({
                text: '登录密码不能为空',
                type: 'warn',
                width: '4rem'
              })
            } else {
              this.passwordLogin()
            }
          } else if (res.status === '400001001') {
            this.$vux.toast.show({
              text: '手机号未注册',
              type: 'warn',
              width: '4rem'
            })
          } else {
            this.$vux.toast.show({
              text: res.message,
              type: 'warn',
              width: '4rem'
            })
          }
        })
      }
    },
    passwordLogin () {
      api.login({
        token: this.tokenval,
        timestamp: timeStamp,
        mobile: this.mobileval,
        password: this.passwordval,
        from: 0,
        loginType: 0,
        authCode: this.$store.state.wxCode || ''
      }).then(res => {
        console.log(JSON.stringify(res))
        if (res.status === '200') {
          localStorage.setItem('status', '1')
          localStorage.setItem('userid', res.data.userId)
          localStorage.setItem('userk', res.data.userKey)
          if (utils.getQueryString('inviteCode')) {
            window.location.replace(process.env.BASE_URL + '/middleBack')
          } else {
            window.location.replace(localStorage.getItem('wxLastUrl'))
          }
        } else if (res.status === '400001001') {
          this.$vux.toast.show({
            text: '用户不存在',
            type: 'warn',
            width: '4rem'
          })
          utils.redirectWx('-2')
        } else {
          this.$vux.toast.show({
            text: res.message,
            type: 'warn',
            width: '4rem'
          })
        }
      })
    },
    next () {
      // 验证码登录
      var self = this
      if (this.mobileval === '') {
        this.$vux.toast.show({
          text: '请输入手机号',
          type: 'warn',
          width: '4rem'
        })
      } else if (this.$refs.mobile01.valid === false) {
        this.$vux.toast.show({
          text: '请输入正确手机号',
          type: 'warn',
          width: '4rem'
        })
      } else if (this.codeval === '') {
        this.$vux.toast.show({
          text: '请输入短信验证码',
          type: 'warn',
          width: '4rem'
        })
      } else {
        api.check({
          token: this.tokenval,
          timestamp: timeStamp,
          mobile: this.mobileval
        }).then(res => {
          if (res.status === '400001002') {
            this.$vux.toast.hide()
            api.validate({
              token: self.tokenval,
              timestamp: timeStamp,
              mobile: self.mobileval,
              type: 1,
              sendType: 5,
              vcode: self.codeval,
              from: 0
            }).then(res => {
              if (res.status === '200') {
                self.vcodeLogin()
              }
            })
          } else if (res.status === '400001001') {
            this.$vux.toast.show({
              text: '手机号未注册',
              type: 'warn',
              width: '4rem'
            })
          } else {
            this.$vux.toast.show({
              text: res.message,
              type: 'warn',
              width: '4rem'
            })
          }
        })
      }
    },
    vcodeLogin () {
      api.login({
        token: this.tokenval,
        timestamp: timeStamp,
        mobile: this.mobileval,
        from: 0,
        loginType: 1,
        vcode: this.codeval,
        authCode: this.$store.state.wxCode || ''
      }).then(res => {
        console.log(res)
        if (res.status === '200') {
          localStorage.setItem('status', '1')
          localStorage.setItem('userid', res.data.userId)
          localStorage.setItem('userk', res.data.userKey)
          this.$store.commit('changeIndexConf', {
            userID: res.data.userId,
            userkey: res.data.userKey
          })
          if (utils.getQueryString('inviteCode')) {
            window.location.replace(process.env.BASE_URL + '/middleBack')
          } else {
            window.location.replace(localStorage.getItem('wxLastUrl'))
          }
        } else if (res.status === '400001001') {
          this.$vux.toast.show({
            text: '用户不存在',
            type: 'warn',
            width: '4rem'
          })
          utils.redirectWx('-2')
        } else {
          this.$vux.toast.show({
            text: res.message,
            type: 'warn',
            width: '4rem'
          })
        }
      })
    },
    setTime () {
      if (this.start) {
        return '重新发送(' + this.time + ')'
      } else {
        return '发送验证码'
      }
    },
    timeFinish () {
      this.start = false
      this.time = 60
    }
  }
}
</script>

